import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Modal, Drawer } from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import { queryRule } from './service';
import {history} from "umi";
import request from "@/utils/request";

const TableList = () => {
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [delValue, setDelValue] = useState({});
  const [authorityValues,setAuthorityValues] = useState({})

  useEffect(
    ()=>{
      request(`/api/client/getAuthority`).then(res=>{
        if (res.Code != 0 ){
          console.log(res.Msg)
        }else{
          setAuthorityValues(res.Data)
        }
      })

    }
    ,[])

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    request(`/api/client/del?ClientId=${delValue.ClientId}`).then(res=>{
      if (res.Code != 0 ){
        message.error(res.Msg)
      }
    })
    setIsModalVisible(false);
    message.success('删除成功！');

    location.reload()
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };


  const columns = [
    {
      title: '用户ID',
      dataIndex: 'ClientId',
      hideInTable: true,
    },
    {
      title: '用户名',
      dataIndex: 'Name',
    },
    {
      title: '权限',
      dataIndex: 'Authority',
      hideInForm: true,
      render: (text) => {
        let result = ""
        if (text != "-"){
          for (let i = 0; i < text.length; i++) {
            if (result != ""){
              result += ", "
            }
            if (authorityValues[text[i]]) {
              result += authorityValues[text[i]]
            }else{
              result += text[i]
            }
          }
        }else{
          return "-"
        }

        return result
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>

            <a onClick={()=>{
              history.push({
                pathname: '/userRegister',
                query: {
                  clientId: record.ClientId,
                },
              })
            }}>更新权限</a>
            <Divider type="vertical" />
            <a onClick={()=>{
              history.push({
                pathname: '/userRegister',
                query: {
                  clientId: record.ClientId,
                  updatePassword: true,
                },
              })
            }}>更新密码</a>
            <Divider type="vertical" />
            <a
              onClick={()=>{
                setDelValue(record)
                showModal()
              }}
            >
              删除
            </a>
          </>
        )
      },
    },
  ];

  const request2 = async(
      // 第一个参数 params 查询表单和 params 参数的结合
      // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
      params ,
      sorter,
      filter,
    ) => {
    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    console.log(params)

    const result = await queryRule({...params,sorter,filter});
    if (result.Code != 0) {
      message.error(result.Msg)
      return
    }
    console.log(result)
    return {
      data:result.Data.Data,
      success:result.Code === 0,
      total:result.Data.Total,
    };
  }


  return (
    <PageContainer>
      <ProTable
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="ClientId"
        search={false}
        options={false}
        toolBarRender={() => [
          <Button type="primary" onClick={() => history.push({
            pathname: '/userRegister',
          })}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        // request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        request={request2}
        columns={columns}
      />
      <Modal title="删除用户" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <p>是否确定删除{delValue.Name}用户</p>
      </Modal>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
